package api

import (
    "encoding/json"
    "net/http"
    "roy/common/data"
)

// login 登录接口
func login(w http.ResponseWriter, r *http.Request) {
    var result Result
    var params Params
    if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
        result.Code = 201
        result.Message = "非法参数"
        json.NewEncoder(w).Encode(result)
        return
    }
    sess := globalSession.SessionStart(w, r)
    info := sess.Get("userinfo")
    if info != nil {
        result.Code = 200
        result.Message = "已登录"
        result.Data = info.(map[string]string)
        json.NewEncoder(w).Encode(result)
        return
    }
    username := params.Username
    password := params.Password
    if username == "" || password == "" {
        result.Code = 202
        result.Message = "用户名和密码不能为空"
        json.NewEncoder(w).Encode(result)
        return
    }
    sql := "select id,username,password,mobile,`status` from `yunduan_user` where username='" + username + "'"
    row := data.GetRow(sql)
    id := ""
    uname := ""
    pwd := ""
    mobile := ""
    status := ""
    row.Scan(&id, &uname, &pwd, &mobile, &status)
    if id == "" {
        result.Code = 400
        result.Message = "用户名或密码错误"
        json.NewEncoder(w).Encode(result)
        return
    }
    rst := data.Getmd5(pwdPrefix, password)
    if rst != pwd {
        result.Code = 401
        result.Message = "用户名或密码错误"
        json.NewEncoder(w).Encode(result)
        return
    }
    m := make(map[string]string, 0)
    m["id"] = id
    m["username"] = uname
    m["password"] = pwd
    m["mobile"] = mobile
    m["status"] = status
    result.Code = 200
    result.Message = "登录成功"
    result.Data = m
    sess.Set("userinfo", m)
    json.NewEncoder(w).Encode(result)
    return
}
